package com.module.framework.handler.security;

import com.alibaba.fastjson.JSON;
import com.module.framework.domain.ResponseResult;
import com.module.framework.enums.AppHttpCodeEnum;
import com.module.framework.utils.WebUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author JiHuiQin
 * @Date 2022/2/7 18:02
 * @Version 1.0
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

	/**
	 * 处理异常，认证失败
	 *
	 * @param request
	 * @param response
	 * @param e
	 * @throws IOException
	 * @throws ServletException
	 */
	@Override
	public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
		e.printStackTrace();

		ResponseResult result = null;

		if (e instanceof BadCredentialsException) {
			result = ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_ERROR.getCode(), e.getMessage());
		} else if (e instanceof InsufficientAuthenticationException) {
			result = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
		} else {
			result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR.getCode(), e.getMessage());
		}

		String json = JSON.toJSONString(result);
		WebUtils.renderString(response, json);
	}
}
